<template>
    <el-dialog v-model="visible" title="客户护理设置" width="90%">
        <!-- 查询区域 -->
        <el-form :inline="true" class="form-bar">
            <el-form-item label="护理级别:">
                <el-select v-model.number="levelId" placeholder="请选择护理级别" @change="handleLevelChange"
                    style="width: 200px">
                    <el-option label="请选择" :value="null" />
                    <el-option v-for="item in levelList" :key="item.levelId" :label="item.levelName"
                        :value="item.levelId" />
                </el-select>
            </el-form-item>
            <el-form-item label="项目名称:">
                <el-input v-model="searchName" placeholder="请输入项目名称" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleSearch">查询</el-button>
                <el-button type="default" @click="handleReset">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 表格 -->
        <el-table :data="tableData" border style="width: 100%; background: #f5f7fa;"
            :header-cell-style="{ background: '#f9fafc', color: '#333', textAlign: 'center' }"
            :cell-style="{ textAlign: 'center' }">
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="projectId" label="编号" width="100" />
            <el-table-column prop="name" label="名称" />
            <el-table-column prop="price" label="价格" />
            <el-table-column prop="cycle" label="执行周期" />
            <el-table-column prop="frequency" label="执行次数" />
            <el-table-column label="服务购买时间">
                <template #default="scope">
                    <span>{{ formatDate(new Date(scope.row.startDate)) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="购买数量">
                <template #default="scope">
                    <el-input-number v-model="scope.row.quantity" :min="1" style="width: 100%" />
                </template>
            </el-table-column>
            <el-table-column label="购买时长（月）">
                <template #default="scope">
                    <el-select v-model="scope.row.months" placeholder="请选择" style="width: 100%">
                        <el-option v-for="m in 6" :key="m" :label="`${m}个月`" :value="m" />
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column label="服务到期时间">
                <template #default="scope">
                    {{ calculateEndDate(scope.row.startDate, scope.row.months) }}
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination v-model:current-page="pagination.cur" v-model:page-size="pagination.size"
            :total="pagination.total" :page-sizes="[5, 10, 20]" layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" class="pagination-bar" />

        <!-- 按钮 -->
        <div class="footer-bar">
            <el-button type="danger" @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="handleConfirm">确认</el-button>
        </div>
    </el-dialog>
</template>

<script setup>
import { ref, defineExpose, defineEmits, inject } from 'vue'
import { ElMessage } from 'element-plus'
import qs from 'qs'

const axios = inject("axios")
const visible = ref(false)
const clientId = ref(null)
const levelId = ref(null)
const searchName = ref('')
const levelList = ref([])
const tableData = ref([])
const pagination = ref({ cur: 1, size: 5, total: 0 })
const fullDataMap = new Map()
const emit = defineEmits(['closeAndRefresh'])

const open = async (incomingClientId) => {
    visible.value = true
    clientId.value = incomingClientId
    levelId.value = null
    searchName.value = ''
    pagination.value.cur = 1
    pagination.value.total = 0
    tableData.value = []
    fullDataMap.clear()
    await loadLevels()
}

const loadLevels = async () => {
    const res = await axios.get('/nursingLevel/pageNursingLevel', {
        params: { cur: 1, number: 100 }
    })
    if (res.data.status === 200) {
        levelList.value = res.data.data || []
        if (levelList.value.length > 0) {
            levelId.value = levelList.value[0].levelId
            await fetchAllProjects()
            pagination.value.total = fullDataMap.size
            updateTableData()
        }
    } else {
        ElMessage.warning(res.data.msg || '加载护理级别失败')
    }
}

const fetchAllProjects = async () => {
    fullDataMap.clear()
    let page = 1
    const pageSize = 50
    let hasMore = true

    while (hasMore) {
        const res = await axios.get('/levelProjectLink/getIncludedProjects', {
            params: {
                cur: page,
                number: pageSize,
                levelId: levelId.value,
                name: searchName.value
            }
        })
        if (res.data.status === 200) {
            const list = res.data.data || []
            list.forEach(item => {
                fullDataMap.set(item.projectId, {
                    ...item,
                    startDate: formatDate(new Date()),
                    quantity: 1,
                    months: 3
                })
            })
            hasMore = list.length === pageSize
            page++
        } else {
            ElMessage.warning(res.data.msg || '项目加载失败')
            break
        }
    }
}

const updateTableData = () => {
    const allData = Array.from(fullDataMap.values())
    const start = (pagination.value.cur - 1) * pagination.value.size
    const end = start + pagination.value.size
    tableData.value = allData.slice(start, end)
}

const handleConfirm = async () => {
    const allData = Array.from(fullDataMap.values())
    for (const row of allData) {
        if (!row.startDate || !row.quantity || !row.months) {
            ElMessage.warning(`项目「${row.name}」请填写完整信息`)
            return
        }
        const start = new Date(row.startDate)
        const end = new Date(start)
        end.setMonth(start.getMonth() + row.months)

        const params = {
            clientId: clientId.value,
            projectId: row.projectId,
            levelId: levelId.value,
            startDate: formatDate(start),
            endDate: formatDate(end),
            quantity: row.quantity
        }

        try {
            const res = await axios.post('/clientNursingProject/addClientNursingProject',
                qs.stringify(params),
                { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
            )
            if (res.data.status !== 200) throw new Error(res.data.msg)
        } catch (err) {
            ElMessage.error(`项目「${row.name}」提交失败：${err.message}`)
            return
        }
    }

    ElMessage.success('所有项目提交成功')
    visible.value = false
    emit('closeAndRefresh')
}

const handleCancel = () => {
    visible.value = false
    fullDataMap.clear()
    emit('closeAndRefresh')
}

const handleSizeChange = (size) => {
    pagination.value.size = size
    pagination.value.cur = 1
    updateTableData()
}

const handleCurrentChange = (page) => {
    pagination.value.cur = page
    updateTableData()
}

const handleSearch = async () => {
    pagination.value.cur = 1
    await fetchAllProjects()
    pagination.value.total = fullDataMap.size
    updateTableData()
}

const handleReset = async () => {
    searchName.value = ''
    pagination.value.cur = 1
    await fetchAllProjects()
    pagination.value.total = fullDataMap.size
    updateTableData()
}

const handleLevelChange = async () => {
    fullDataMap.clear()
    pagination.value.cur = 1
    await fetchAllProjects()
    pagination.value.total = fullDataMap.size
    updateTableData()
}

const formatDate = (date) => {
    const y = date.getFullYear()
    const m = String(date.getMonth() + 1).padStart(2, '0')
    const d = String(date.getDate()).padStart(2, '0')
    return `${y}-${m}-${d}`
}

const calculateEndDate = (startDate, months) => {
    if (!startDate || !months) return ''
    const start = new Date(startDate)
    start.setMonth(start.getMonth() + months)
    return formatDate(start)
}

defineExpose({ open })
</script>

<style scoped>
.form-bar {
    display: flex;
    gap: 10px;
    align-items: center;
    margin-bottom: 20px;
}

.footer-bar {
    text-align: right;
    margin-top: 2%;
}

.el-dialog__title {
    font-size: 27.2px;
}

.el-table th {
    text-align: center !important;
    background-color: #f9fafc;
    color: #333;
}

.el-table td {
    text-align: center;
}

.pagination-bar {
    margin-top: 2%;
    margin-bottom: 2%;
    text-align: right;
}
</style>
